<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;


class IndexController extends Controller
{
    public function actionIndex()
    {
        $data = $this->getData();
        return $this->render('index', ['data' => $data]);
    }

    public function getData()
    {
        $category1 = $this->getCategory1();
        if ($category1 && is_array($category1)) {
            foreach ($category1 as &$category1Item) {
                $category2 = $this->getCategory2($category1Item['id']);
                if ($category2 && is_array($category2)) {
                    foreach ($category2 as &$category2Item) {
                        $category2Item['books'] = $this->getBook($category1Item['id'], $category2Item['id']);
                    }
                }
                $category1Item['son'] = $category2;
            }
        }
        return $category1;
    }

    public function getCategory1()
    {
        $sql    = "
            select `id`,`name`,`pid`,`type` from `category` where `type` = 0 and `is_delete` = 0
        ";
        $result = Yii::$app->db->createCommand($sql)->queryAll();
        if (!$result) {
            return array();
        }
        return $result;
    }

    public function getCategory2($pid)
    {
        $sql    = "
            select `id`,`name`,`pid`,`type` from `category` where `pid` = {$pid} and `is_delete` = 0
        ";
        $result = Yii::$app->db->createCommand($sql)->queryAll();
        if (!$result) {
            return array();
        }
        return $result;
    }

    public function getBook($cid1, $cid2)
    {
        $sql    = "
            select `id`,`name`,`path`,`category1`,`category2`,`create_time`,`update_time` from `books` where `category1`={$cid1} and `category2`={$cid2}
        ";
        $result = Yii::$app->db->createCommand($sql)->queryAll();
        if (!$result) {
            return array();
        }
        return $result;
    }
}
